import { useEffect, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { FilterIcon, SlidersIcon } from 'lucide-react';
import ImageLoader from '../components/UI/ImageLoader';
import Pagination from '../components/UI/Pagination';
import Filter from '../components/UI/Filter';
// Sample review data
const allReviews = [{
  id: 'sony-wh1000xm5',
  title: 'Sony WH-1000XM5: The New King of ANC Headphones?',
  excerpt: "Our in-depth analysis of Sony's latest flagship noise-cancelling headphones reveals impressive improvements.",
  image: 'https://images.unsplash.com/photo-1618366712010-f4ae9c647dcb?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80',
  category: 'audio',
  brand: 'sony',
  rating: 4.8,
  date: '2023-05-15'
}, {
  id: 'macbook-m2-pro',
  title: 'Apple M2 Pro MacBook: Performance That Redefines Mobile Computing',
  excerpt: "We pushed Apple's latest silicon to its limits through our comprehensive benchmark suite.",
  image: 'https://images.unsplash.com/photo-1517336714731-489689fd1ca8?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1026&q=80',
  category: 'compute',
  brand: 'apple',
  rating: 4.9,
  date: '2023-06-20'
}, {
  id: 'samsung-s23-ultra',
  title: 'Samsung Galaxy S23 Ultra: Computational Photography Mastery',
  excerpt: "Samsung's flagship smartphone camera system sets new standards for mobile photography.",
  image: 'https://images.unsplash.com/photo-1610945415295-d9bbf067e59c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
  category: 'mobile',
  brand: 'samsung',
  rating: 4.7,
  date: '2023-04-10'
}, {
  id: 'lg-c3-oled',
  title: 'LG C3 OLED: The Ultimate Gaming TV for Next-Gen Consoles',
  excerpt: "LG's latest OLED delivers incredible picture quality and gaming performance that will satisfy even the most demanding players.",
  image: 'https://images.unsplash.com/photo-1593305841991-05c297ba4575?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1057&q=80',
  category: 'visual',
  brand: 'lg',
  rating: 4.9,
  date: '2023-03-05'
}, {
  id: 'apple-studio-display',
  title: 'Apple Studio Display: Professional Excellence at a Premium',
  excerpt: 'Apple\'s 27-inch 5K display brings Retina quality and professional features to creative workflows.',
  image: 'https://images.unsplash.com/photo-1633114128174-2f8aa49759b0?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80',
  category: 'visual',
  brand: 'apple',
  rating: 4.5,
  date: '2024-01-12'
}, {
  id: 'rtx-4090',
  title: 'NVIDIA RTX 4090: Pushing the Boundaries of GPU Performance',
  excerpt: 'The flagship Ada Lovelace GPU delivers unprecedented performance, but comes with some significant considerations.',
  image: 'https://images.unsplash.com/photo-1591488320449-011701bb6704?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1074&q=80',
  category: 'compute',
  brand: 'nvidia',
  rating: 4.6,
  date: '2023-02-15'
}, {
  id: 'apple-airpods-pro-2',
  title: 'Apple AirPods Pro 2: Refined Excellence in a Familiar Package',
  excerpt: "The second-generation AirPods Pro bring meaningful improvements to Apple's premium earbuds.",
  image: 'https://images.unsplash.com/photo-1600294037681-c80b4cb5b434?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
  category: 'audio',
  brand: 'apple',
  rating: 4.5,
  date: '2023-01-20'
}, {
  id: 'asus-rog-ally',
  title: 'ASUS ROG Ally: A Worthy Steam Deck Competitor',
  excerpt: 'ASUS enters the handheld gaming PC market with impressive hardware, but software quirks remain.',
  image: 'https://images.unsplash.com/photo-1593118247619-e2d6f056869e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
  category: 'compute',
  brand: 'asus',
  rating: 4.3,
  date: '2023-07-05'
}, {
  id: 'google-pixel-7-pro',
  title: 'Google Pixel 7 Pro: AI-Powered Photography Excellence',
  excerpt: 'Google continues to push the boundaries of computational photography with its latest flagship smartphone.',
  image: 'https://images.unsplash.com/photo-1598327105666-5b89351aff97?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2027&q=80',
  category: 'mobile',
  brand: 'google',
  rating: 4.6,
  date: '2022-12-10'
}, {
  id: 'samsung-odyssey-g9',
  title: 'Samsung Odyssey G9: The Ultimate Ultrawide Gaming Monitor',
  excerpt: 'This massive 49-inch curved monitor delivers an immersive gaming experience, but requires serious GPU power.',
  image: 'https://images.unsplash.com/photo-1616588589676-62b3bd4ff6d2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2064&q=80',
  category: 'visual',
  brand: 'samsung',
  rating: 4.7,
  date: '2022-11-15'
}];
const Reviews = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [currentPage, setCurrentPage] = useState(1);
  const [reviews, setReviews] = useState(allReviews);
  const [showFilters, setShowFilters] = useState(false);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [selectedBrands, setSelectedBrands] = useState<string[]>([]);
  const [sortBy, setSortBy] = useState('date');
  const itemsPerPage = 6;
  // Get category title for heading
  const getCategoryTitle = () => {
    if (selectedCategories.length === 1) {
      const category = categoryOptions.find(c => c.id === selectedCategories[0]);
      if (category) {
        switch (category.id) {
          case 'audio':
            return 'Audio Sanctuary';
          case 'visual':
            return 'Visual Frontier';
          case 'compute':
            return 'Compute Core';
          case 'mobile':
            return 'Mobile Nexus';
          default:
            return category.label;
        }
      }
    }
    return 'Product Reviews';
  };
  useEffect(() => {
    document.title = `${getCategoryTitle()} | TronoraHub`;
  }, [selectedCategories]);
  const categoryOptions = [{
    id: 'audio',
    label: 'Audio'
  }, {
    id: 'visual',
    label: 'Visual'
  }, {
    id: 'compute',
    label: 'Compute'
  }, {
    id: 'mobile',
    label: 'Mobile'
  }];
  const brandOptions = [{
    id: 'apple',
    label: 'Apple'
  }, {
    id: 'samsung',
    label: 'Samsung'
  }, {
    id: 'sony',
    label: 'Sony'
  }, {
    id: 'lg',
    label: 'LG'
  }, {
    id: 'nvidia',
    label: 'NVIDIA'
  }, {
    id: 'asus',
    label: 'ASUS'
  }, {
    id: 'google',
    label: 'Google'
  }];
  const sortOptions = [{
    id: 'date',
    label: 'Most Recent'
  }, {
    id: 'rating',
    label: 'Highest Rated'
  }, {
    id: 'title',
    label: 'Alphabetical'
  }];
  // Check for URL parameters
  useEffect(() => {
    const categoryParam = searchParams.get('category');
    if (categoryParam) {
      setSelectedCategories([categoryParam.toLowerCase()]);
      setShowFilters(true);
    }
  }, [searchParams]);
  useEffect(() => {
    // Apply filters and sorting
    let filteredReviews = [...allReviews];
    // Filter by category
    if (selectedCategories.length > 0) {
      filteredReviews = filteredReviews.filter(review => selectedCategories.includes(review.category));
    }
    // Filter by brand
    if (selectedBrands.length > 0) {
      filteredReviews = filteredReviews.filter(review => selectedBrands.includes(review.brand));
    }
    // Apply sorting
    if (sortBy === 'date') {
      filteredReviews.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
    } else if (sortBy === 'rating') {
      filteredReviews.sort((a, b) => b.rating - a.rating);
    } else if (sortBy === 'title') {
      filteredReviews.sort((a, b) => a.title.localeCompare(b.title));
    }
    setReviews(filteredReviews);
    setCurrentPage(1); // Reset to first page when filters change
  }, [selectedCategories, selectedBrands, sortBy]);
  // Get current page items
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = reviews.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(reviews.length / itemsPerPage);
  return <div className="w-full bg-[#0d0d10] pt-24 pb-16">
      <div className="container mx-auto px-4">
        <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8">
          <h1 className="text-3xl md:text-4xl font-bold font-display mb-4 md:mb-0">
            {getCategoryTitle()}
          </h1>
          <div className="flex items-center">
            <button onClick={() => setShowFilters(!showFilters)} className="flex items-center px-4 py-2 bg-[#151518] rounded-lg hover:bg-[#1a1a1d] text-sm mr-4">
              <FilterIcon size={16} className="mr-2" />
              Filters
            </button>
            <div className="relative">
              <select value={sortBy} onChange={e => setSortBy(e.target.value)} className="appearance-none bg-[#151518] px-4 py-2 pr-8 rounded-lg text-sm focus:outline-none focus:ring-1 focus:ring-[#4361ee]">
                {sortOptions.map(option => <option key={option.id} value={option.id}>
                    {option.label}
                  </option>)}
              </select>
              <SlidersIcon size={16} className="absolute right-2 top-1/2 transform -translate-y-1/2 pointer-events-none" />
            </div>
          </div>
        </div>
        {showFilters && <div className="mb-8 p-4 bg-[#0f0f12] rounded-lg border border-[#4361ee]/20">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Filter label="Category" options={categoryOptions} selectedOptions={selectedCategories} onChange={setSelectedCategories} />
              </div>
              <div>
                <Filter label="Brand" options={brandOptions} selectedOptions={selectedBrands} onChange={setSelectedBrands} />
              </div>
            </div>
          </div>}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {currentItems.map(review => <Link key={review.id} to={`/review/${review.id}`} className="group card overflow-hidden hover:shadow-lg hover:shadow-[#4361ee]/10 transition-all">
              <div className="aspect-[16/9] relative">
                <ImageLoader src={review.image} alt={review.title} className="w-full h-full" />
              </div>
              <div className="p-6">
                <div className="flex items-center justify-between mb-3">
                  <span className="text-xs font-medium px-3 py-1 rounded-full bg-[#151518] text-[#4361ee]">
                    {review.category.charAt(0).toUpperCase() + review.category.slice(1)}
                  </span>
                  <div className="flex items-center">
                    <span className="text-sm font-medium text-[#06d6a0]">
                      {review.rating.toFixed(1)}
                    </span>
                    <span className="text-[#8a8f98] text-xs ml-1">/5.0</span>
                  </div>
                </div>
                <h3 className="font-display font-bold text-lg mb-2 group-hover:text-[#4361ee] transition-colors line-clamp-2">
                  {review.title}
                </h3>
                <p className="text-[#8a8f98] text-sm line-clamp-2 mb-4">
                  {review.excerpt}
                </p>
                <div className="text-xs text-[#8a8f98]">
                  {new Date(review.date).toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
              })}
                </div>
              </div>
            </Link>)}
        </div>
        {reviews.length === 0 && <div className="text-center py-16">
            <h3 className="text-xl font-bold mb-2">
              No reviews match your filters
            </h3>
            <p className="text-[#8a8f98]">
              Try adjusting your filters to see more results
            </p>
          </div>}
        {reviews.length > itemsPerPage && <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={setCurrentPage} />}
      </div>
    </div>;
};
export default Reviews;